/* eslint-disable array-callback-return */
'use strict';

const Sequelize = require('sequelize');
const Op = Sequelize.Op;

const Service = require('egg').Service;
class SkuService extends Service {
  //添加规格key和value
  async createKeyValue(dataObj) {
    const { ctx, service } = this;
    console.log(dataObj);
    let obj = {
      keyName: dataObj.keyName,
      project_id: dataObj.project_id,
      valueName: '',
    };
    let res = await service.shop.attributes.keyCreate(obj);
    let valueString = dataObj.valueName;
    for (let i = 0; i < valueString.length; i++) {
      await service.shop.attributes.valueCreate({
        attribute_value: valueString[i].value,
        attribute_id: res.dataValues.id,
        photo: valueString[i].photo,
      });
    }
    return ctx.response.success('成功');
  }
  //获取规格key和value
  async getKeyValue(id, dataObj) {
    try {
      const { AttributesKey, AttributesValue } = this.app.model.Tables.Shop;
      console.log(dataObj.keyName);

      if (!dataObj.keyName) {
        const result = await AttributesKey.findAll({
          where: {
            project_id: id,
          },
          attributes: ['id', 'keyName'],
          include: [
            {
              model: AttributesValue,
              attributes: ['id', 'attribute_id', 'attribute_value', 'photo'],
            },
          ],
        });
        if (result) {
          return this.ctx.response.success(result);
        }
      } else {
        const res = await AttributesKey.findAll({
          where: {
            project_id: id,
            id: {
              [Op.in]: dataObj.keyName,
            },
          },
          attributes: ['id', 'keyName'],
          include: [
            {
              model: AttributesValue,
              attributes: ['id', 'attribute_id', 'attribute_value', 'photo'],
            },
          ],
        });
        return res;
      }

      return this.ctx.response.error('找不到该商品规格信息');
    } catch (error) {
      return this.ctx.response.error(error.message);
    }
  }
  //修改规格key和value
  async updateKeyValue(dataObj) {
    const { ctx, service } = this;
    try {
      const { AttributesKey, AttributesValue } = this.app.model.Tables.Shop;

      const result = await AttributesKey.findOne({
        where: {
          id: dataObj.keyId,
        },
      });

      if (result) {
        const resultG = await result.update({
          ...dataObj,
          valueName: '',
        });
        let arr = dataObj.valueName;
        for (let i = 0; i < arr.length; i++) {
          let res;
          try {
            res = await AttributesValue.findOne({
              where: {
                id: arr[i].id,
              },
            });
          } catch (error) {
            await service.shop.attributes.valueCreate({
              attribute_value: arr[i].value,
              photo: arr[i].photo,
              attribute_id: dataObj.keyId,
            });
          }
          if (res) {
            await res.update({
              id: arr[i].id,
              photo: arr[i].photo,
              attribute_value: arr[i].value,
              attribute_id: dataObj.keyId,
            });
          }
        }
      }
      return result
        ? ctx.response.success('更新成功')
        : ctx.response.error('更新失败');
    } catch (error) {
      return ctx.response.error(
        error.message === 'Validation error' ? '已有该商品名称' : error.message
      );
    }
  }
  //删除规格key和value
  async delKeyValue(id) {
    const { ctx } = this;
    try {
      const { AttributesKey } = this.app.model.Tables.Shop;
      const resultGoods = await AttributesKey.destroy({
        where: {
          id,
        },
      });
      return resultGoods > 0
        ? ctx.response.success('删除成功')
        : ctx.response.error('删除失败');
      // if (resultGoods) {
      //   // const resultG = await resultGoods.update({ status: '2' });
      //   return resultG ? (ctx.response.success('删除成功')) : (ctx.response.error(resultG, '更新失败'));
      // }
      // return ctx.response.error('找不到该商品信息');
      // return result > 0 ? (ctx.response.success('删除成功')) : (ctx.response.error('删除失败'));
    } catch (error) {
      return ctx.response.error(
        error.message === 'Validation error' ? '已有该商品名称' : error.message
      );
    }
  }
  //删除value值
  async delValue(id) {
    const { ctx } = this;
    try {
      const { AttributesValue } = this.app.model.Tables.Shop;
      const resultGoods = await AttributesValue.destroy({
        where: {
          id,
        },
      });
      return resultGoods > 0
        ? ctx.response.success('删除成功')
        : ctx.response.error('删除失败');
    } catch (error) {
      return ctx.response.error(
        error.message === 'Validation error' ? '已有该商品名称' : error.message
      );
    }
  }

  // 获取规格
  async show(goods_id) {
    try {
      const { Sku, SkuAttribute, AttributesKey, AttributesValue } =
        this.app.model.Tables.Shop;
      let res = await Sku.findAll({
        where: {
          goods_id,
        },
      });
      if (!res) {
        return this.ctx.response.error('找不到该商品规格信息');
      }
      let keylist = [];
      res.forEach((ele) => {
        let str = ele.dataValues.goods_keys;
        let arr = str.split(',');
        keylist = keylist.concat(arr);
      });
      const arr = await AttributesKey.findAll({
        where: {
          id: {
            [Op.in]: [...new Set(keylist)],
          },
        },
        attributes: ['id', 'keyName'],
        include: [
          {
            model: AttributesValue,
            attributes: ['id', 'attribute_id', 'attribute_value', 'photo'],
          },
        ],
      });
      const result = await Sku.findAll({
        where: {
          goods_id,
        },
        attributes: ['id', 'goods_specs', 'goods_stock', 'goods_price'],
      });
      let obj = {
        property: arr,
        stock_list: result,
      };
      if (result) {
        return this.ctx.response.success(obj);
      }
      return this.ctx.response.error('找不到该商品规格信息');
    } catch (error) {
      return this.ctx.response.error(error.message);
    }
  }

  // 添加规格
  async create(dataObj) {
    const { ctx, service } = this;
    //还需要去操作attributes表添加对应的属性
    const { Sku, Connect, AttributesKey } = this.app.model.Tables.Shop;
    try {
      let goodarr = dataObj.goodarr.map((ele) => {
        return {
          id: ele.id,
          goods_id: dataObj.goods_id,
          goods_keys: dataObj.goods_keys,
          goods_specs: ele.goods_specs,
          goods_stock: ele.goods_stock,
          goods_price: ele.goods_price,
        };
      });

      for (let i = 0; i < goodarr.length; i++) {
        let res = await Sku.findOne({
          where: {
            id: goodarr[i].id,
          },
        });
        if (res) {
          const resultG = await res.update({ ...goodarr[i] });
        } else {
          await Sku.create({
            goods_id: dataObj.goods_id,
            goods_keys: dataObj.goods_keys,
            goods_specs: goodarr[i].goods_specs,
            goods_stock: goodarr[i].goods_stock,
            goods_price: goodarr[i].goods_price,
          });
        }
      }

      return ctx.response.success('操作成功');
    } catch (error) {
      console.log(error);
      return ctx.response.error(
        error.message === 'Validation error' ? '已有该商品规格' : error.message
      );
    }
  }
  // 更新规格
  async update(goods_id, data) {
    const { ctx, service } = this;
    try {
      const { Sku } = this.app.model.Tables.Shop;
      const resultGoods = await Sku.findOne({
        where: {
          goods_id,
        },
      });

      if (resultGoods) {
        const resultG = await resultGoods.update({
          ...data,
        });
        return resultG
          ? ctx.response.success(resultG, '更新成功')
          : ctx.response.error(resultG, '更新失败');
      }
      return ctx.response.error('找不到该商品规格信息');
    } catch (error) {
      return ctx.response.error(
        error.message === 'Validation error' ? '已有该商品名称' : error.message
      );
    }
  }
  // 删除规格
  async destroy(id) {
    const { ctx } = this;
    try {
      const { Sku } = this.app.model.Tables.Shop;
      const resultGoods = await Sku.destroy({
        where: {
          id,
        },
      });
      return resultGoods > 0
        ? ctx.response.success('删除成功')
        : ctx.response.error('删除失败');
      // if (resultGoods) {
      //   // const resultG = await resultGoods.update({ status: '2' });
      //   return resultG ? (ctx.response.success('删除成功')) : (ctx.response.error(resultG, '更新失败'));
      // }
      // return ctx.response.error('找不到该商品信息');
      // return result > 0 ? (ctx.response.success('删除成功')) : (ctx.response.error('删除失败'));
    } catch (error) {
      return ctx.response.error(
        error.message === 'Validation error' ? '已有该商品名称' : error.message
      );
    }
  }
}

module.exports = SkuService;
